package main;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.sql.ResultSetMetaData;
 import java.sql.SQLException;*/
import java.sql.Statement;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import java.net.*;
import java.io.*;
import java.io.*;

public class server extends JPanel implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JButton cntBtn;
	private JButton createBtn;
	private JLabel[] labelArray;
	private JLabel tableNameLb;
	private JTextField tableNameTF;
	private JTextField[] txtFldArray;
	private JCheckBox[] checkBoxArray;
	private JRadioButton[] radioBtnArray;
	private ButtonGroup radioBtnGroup;

	static final String cntAction = "cntAction";
	static final String createAction = "createAction";

	// public static Connection connection = null;
	static final String databasePath = ".\\database\\";
	static final String databaseName = "database.txt";
	// static final String username = "sa";
	// static final String password = "password";
	private JTable result;
	private DefaultTableModel model;
	private Vector<String> colVector;
	static final int selectCmd = 0;
	static final int insertCmd = 1;
	static final int updateCmd = 2;
	static final int deleteCmd = 3;
	private byte[] revMessage;
	private byte[] sendMessage;

	private File database;
	private int numberOfTable;
	private String[] tableName;
	private String[][] colName;

	public server() {
		super(new BorderLayout());
		this.setPreferredSize(new Dimension(600, 350));

		JPanel p1 = new JPanel();
		// Button connect to Database
		cntBtn = new JButton("Connect to DB");
		cntBtn.setPreferredSize(new Dimension(120, 120));
		cntBtn.setActionCommand(cntAction);
		p1.add(cntBtn);

		JLabel lb = new JLabel("Create table:");
		JPanel pTemp1 = new JPanel();
		pTemp1.add(lb);

		JPanel pTemp2 = new JPanel();
		tableNameLb = new JLabel("Table name: ");
		tableNameTF = new JTextField();
		tableNameTF.setPreferredSize(new Dimension(120, 20));
		pTemp2.add(tableNameLb);
		pTemp2.add(tableNameTF);

		JPanel p2 = new JPanel();
		p2.setLayout(new GridLayout(13, 4));

		labelArray = new JLabel[10];
		txtFldArray = new JTextField[10];
		checkBoxArray = new JCheckBox[10];
		radioBtnArray = new JRadioButton[10];
		radioBtnGroup = new ButtonGroup();
		for (int i = 0; i < 10; i++) {
			labelArray[i] = new JLabel("Column " + (i + 1) + ":");
			txtFldArray[i] = new JTextField();
			txtFldArray[i].setPreferredSize(new Dimension(120, 20));
			checkBoxArray[i] = new JCheckBox("int");
			radioBtnArray[i] = new JRadioButton("Primary key");
			radioBtnGroup.add(radioBtnArray[i]);

			p2.add(labelArray[i]);
			p2.add(txtFldArray[i]);
			p2.add(checkBoxArray[i]);
			p2.add(radioBtnArray[i]);
		}
		// JPanel pTemp3 = new JPanel();
		createBtn = new JButton("Create table");
		createBtn.setActionCommand(createAction);
		p2.add(createBtn);

		JPanel pT = new JPanel();
		pT.add(pTemp1);
		pT.add(pTemp2);

		JPanel p3 = new JPanel();
		p3.setLayout(new BorderLayout());
		p3.add(pT, BorderLayout.PAGE_START);
		p3.add(p2);

		this.add(p1, BorderLayout.LINE_START);
		this.add(p3, BorderLayout.CENTER);

		cntBtn.addActionListener(this);
		createBtn.addActionListener(this);

		tableName = new String[10];
		colName = new String[10][10];
	}

	public static void RunServer() {
		try {
			ServerSocket s = new ServerSocket(1234);

			do {
				Socket ss = s.accept();

				// create inputstream outputstream
				InputStream is = ss.getInputStream();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));

				OutputStream os = ss.getOutputStream();
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
						os));

				String receiveMsg;

				do {
					// receive data from Client
					receiveMsg = br.readLine();
					System.out.println("Client : " + receiveMsg);
					// test key form Client so that disconnect
					if (receiveMsg.equalsIgnoreCase("quit")) {
						System.out.print("Client has left ");
						break;
					} else {
						System.out.println("run query ");

						// sent data to client
						// system.in
						DataInputStream din = new DataInputStream(System.in);
						String k = din.readLine();
						bw.write(k);
						bw.flush();
					}
				} while (true);
				br.close();
				bw.close();
				ss.close();

			} while (true);
		} catch (Exception exc) {
			System.err.println("Error: ");
			exc.printStackTrace();
		}
	}

	//
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		// Connect to DB button clicked
		database = new File(databasePath + databaseName);
		if (cntAction == e.getActionCommand()) {
			String[] values = { "dwqdw", "12w3e", "r32f32", null, "r32r32",
					"3232r32", null };
			doInsertCommand("table2", values);
			/*
			 * System.out.print("connecting...\n"); // Mo file chua thong tin
			 * cac bang trong CSDL
			 * 
			 * // Neu chua co file database thi tao ra file moi // so bang ban
			 * dau la 0 if (!database.exists()) { try { FileOutputStream fOut =
			 * new FileOutputStream(database);
			 * System.out.print("Da tao CSDL!\n"); return; } catch (IOException
			 * e1) { // TODO Auto-generated catch block
			 * JOptionPane.showMessageDialog(new JFrame(),
			 * "Khong tao duoc CSDL", "Error Message",
			 * JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } try {
			 * FileInputStream fIn = new FileInputStream(database); Scanner scan
			 * = new Scanner(fIn, "UTF-8"); // Moi bang trong CSDL int iTable =
			 * 0; while (scan.hasNextLine()) { // Lay ra so luong cot
			 * tableName[iTable] = scan.nextLine();
			 * System.out.print(tableName[iTable] + "\n"); String countCol =
			 * scan.nextLine(); int numberOfCol = Integer.valueOf((countCol));
			 * for (int iCol = 0; iCol < numberOfCol; iCol++) { // Lay ra ten
			 * cac cot colName[iTable][iCol] = scan.nextLine();
			 * System.out.print(colName[iTable][iCol] + "\n"); } iTable++; }
			 * numberOfTable = iTable; } catch (FileNotFoundException e1) { //
			 * TODO Auto-generated catch block e1.printStackTrace(); } //
			 * cntBtn.setEnabled(false);
			 */
		}
		// Create table button clicked
		else if (createAction == e.getActionCommand()) {
			// get column of primary key
			int col = -1;
			for (int i = 0; i < 10; i++) {
				if (radioBtnArray[i].isSelected()) {
					col = i;
					break;
				}
			}
			String[] createString = createTable(this.tableNameTF,
					this.txtFldArray, this.checkBoxArray, col);
			File newTableFile = new File(databasePath + createString[0]
					+ ".txt");
			try {
				if (!newTableFile.exists()) {
					FileOutputStream fTable = new FileOutputStream(newTableFile);
					FileWriter fW = new FileWriter(database, true);
					BufferedWriter buffer = new BufferedWriter(fW);
					for (String s : createString) {
						buffer.write(s + "\r\n");
						buffer.flush();
					}
					JOptionPane.showMessageDialog(new JFrame(), "Da tao bang!",
							"Message", JOptionPane.INFORMATION_MESSAGE);
				} else {
					JOptionPane.showMessageDialog(new JFrame(),
							"Ten bang da ton tai!", "Error Message",
							JOptionPane.ERROR_MESSAGE);
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	// do select query command

	//
	public static int sqlCmdClassifier(String s) {
		String s0 = s.trim();
		s0 = s0.toLowerCase();
		String[] temp = s0.split(" ");
		switch (temp[0]) {
		case "select":
			return selectCmd;
		case "insert":
			return insertCmd;
		case "update":
			return updateCmd;
		case "delete":
			return deleteCmd;
		default:
			return -1;
		}
	}

	private String[] createTable(JTextField tableName, JTextField[] colNames,
			JCheckBox[] isInt, int col) {
		int numberOfCol = -1;
		int countPart = 0;
		String[] createString;

		for (int i = 0;; i++) {
			if (colNames[i].getText().isEmpty()) {
				numberOfCol = i + 2;
				break;
			}
		}
		createString = new String[numberOfCol];
		createString[countPart++] = tableName.getText();
		for (int i = 0;; i++) {
			if (colNames[i].getText().isEmpty()) {
				createString[countPart++] = String.valueOf(i);
				break;
			}
		}
		for (int i = 0; i < 10; i++) {
			if (colNames[i].getText().isEmpty())
				break;
			createString[countPart] = colNames[i].getText();
			if (isInt[i].isSelected()) {
				createString[countPart] += ",int";
			}
			if (i == col) {
				createString[countPart++] += ",p";
			} else {
				countPart++;
			}
		}
		return createString;
	}

	private void doInsertCommand(String tableName, String[] values) {
		try {
			File tableFile = new File(databasePath + tableName + ".txt");
			FileReader fIn = new FileReader(tableFile);
			FileWriter fOut = new FileWriter(tableFile, true);
			Scanner scan1 = new Scanner(fIn);

			BufferedWriter buffer = new BufferedWriter(fOut);
			if (!scan1.hasNext()) {
				for (String s : values) {
					buffer.write(s + "\r\n");
					;
					buffer.flush();
				}
				buffer.write("1" + "\r\n");
				buffer.flush();
			} else {
				int numberOfRecord = 0;
				String temp = "";
				while (scan1.hasNextLine()) {
					temp = scan1.nextLine();
				}

				numberOfRecord = Integer.valueOf(temp);
				numberOfRecord++;

				System.out.print(numberOfRecord);
				for (String s : values) {
					buffer.write(s + "\r\n");
					buffer.flush();
				}
				buffer.write(numberOfRecord + "\r\n");
				buffer.flush();
			}
			buffer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void doDelateCommand(String tableName, int numberOfCol,
			int colIndex, String conditionValues) {
		File tableFile = new File(databasePath + tableName + ".txt");
		int[] result;
		int numberOfResult = -1;
		result = new int[100];
		for(int i = 0; i < 100 ; i++){
			result[i] = -1;
		}
		
		try {
			FileReader fIn = new FileReader(tableFile);
		//	FileWriter fOut = new FileWriter(tableFile, true);
			Scanner scan1 = new Scanner(fIn);
            RandomAccessFile ra = new RandomAccessFile(tableFile, "rw");
			int numberOfRecord = 0;
			String temp = "";
			while (scan1.hasNextLine()) {
				temp = scan1.nextLine();
			}
			numberOfRecord = Integer.valueOf(temp);
			scan1.reset();

			String temp2;
			int pos=0;
			int pos2;// = 0;
			for (int i = 0; i < numberOfRecord; i++) {	
				pos2 = 0;
				pos+= Integer.SIZE;
				for (int j =0; j < numberOfCol; j++) {
					temp2 = scan1.nextLine();
					pos2 += temp2.length();
					if (colIndex == j) {
						if (conditionValues == temp2) {
							result[++numberOfResult] = i+1;								
						}
					}
				}
				pos+=pos2;
				 scan1.nextLine();
			}
			for(int i = 0; i < 100 ; i++){
				if(result[i] == -1){
					break;
				}
				//ra.
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {

		JFrame.setDefaultLookAndFeelDecorated(true);

		// Create and set up the window.
		JFrame frame = new JFrame("Server");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Create and set up the content pane.
		JComponent newContentPane = new server();

		newContentPane.setOpaque(true);
		frame.setContentPane(newContentPane);

		// Display the window.
		frame.pack();
		frame.setVisible(true);
		// runser th = new runser();
		// th.start();

	}

}
/*
 * class runser extends Thread{ private int abc; public runser(){
 * super("Child Thread"); } public void run() { try { ServerSocket s = new
 * ServerSocket(1234);
 * 
 * do { Socket ss = s.accept();
 * 
 * // create inputstream outputstream InputStream is = ss.getInputStream();
 * BufferedReader br = new BufferedReader( new InputStreamReader(is));
 * 
 * OutputStream os = ss.getOutputStream(); BufferedWriter bw = new
 * BufferedWriter(new OutputStreamWriter(os));
 * 
 * String receiveMsg;
 * 
 * do { // Statement st; // st = server.connection.createStatement(); //receive
 * data from Client receiveMsg = br.readLine(); System.out.println("Client �: "
 * + receiveMsg); // test key form Client so that disconnect if
 * (receiveMsg.equalsIgnoreCase("quit")) { System.out.print("Client has left ");
 * break; } else { System.out.println("run query "); int i =
 * server.sqlCmdClassifier(receiveMsg); if(i != 0 && i != -1) { // abc =
 * st.executeUpdate(receiveMsg);
 * System.out.println("thuc hien xong cau lenh sql "); }
 * 
 * // sent data to client // system.in DataInputStream din = new
 * DataInputStream(System.in); String k = din.readLine(); bw.write(k);
 * bw.flush(); } } while (true); br.close(); bw.close(); ss.close();
 * 
 * } while (true); } catch (Exception exc) { System.err.println("Error: ");
 * exc.printStackTrace(); } }
 * 
 * }
 */
